# 封住request请求
# 安装request库
import requests
# 导入封装好的日志模块
from common.logs import Logs

# 之前把日志记录器写在类里面时，会导致处理器重复被创建，日志会重复记录，现在挪到外面，就不会重复记录了
logger = Logs("接口请求操作").get_logger()    # 创建日志记录器

# 创建一个request请求的类
class Request:
    # 私有属性
    response = None       # 响应内容
    url = None            # 请求路径
    method = None         # 请求方式
    headers = None        # 请求头
    params = None          # 路径请求参数
    json = None           # 请求体

    def __init__(self, method, url, **kwargs):
        pass

    # 封装一个请求函数
    def request(self, method, url, **kwargs):
        self.url = url
        self.method = method
        if 'headers' in kwargs:
            self.headers = kwargs['headers']
        if 'params' in kwargs:
            self.params = kwargs['params']
        if 'json' in kwargs:
            self.json = kwargs['json']

        try:
            if method == 'get':
                self.response = requests.get(self.url, **kwargs)

            elif method == 'post':
                self.response = requests.post(self.url, **kwargs)

            elif method == 'put':
                self.response = requests.put(self.url, **kwargs)

            elif method == 'delete':
                self.response = requests.delete(self.url, **kwargs)

            else:
                logger.error(f"请求方式{method}错误，请检查！")
                # print(f"请求方式{method}错误，请检查！")

            logger.info(f"请求路径：{self.url}  请求方式：{self.method}  请求头：{self.headers}")
            logger.info(f"响应code值：{self.response.status_code}  响应内容：{self.response.json()}")

            return self.response
        except Exception as e:
            logger.error(f"请求异常！异常信息为：{e}")
            # print(f"请求异常！异常信息为：{e}")

    # 封装 提取响应结果data中 变量的函数
    def data_extract_value(self, extract_value_name):
        if self.response.status_code == '200':      # 如果请求成功 就提取data的变量
            if 'data' in self.response.json() and extract_value_name in self.response.json()['data']:   # 判断提取的变量是否存在
                return self.response.json()['data'][extract_value_name]

            else:       # 提取的变量不存在
                logger.error(f"响应结果-data中，没有{extract_value_name}的字段")
                # print(f"响应结果-data中，没有{extract_value_name}的字段")
        else:
            logger.error(f"接口没有请求成功！请检查！响应结果为：{self.response.json()}")
            # print(f"接口没有请求成功！请检查！响应结果为：{self.response.json()}")
            return None

        logger.info(f"请求路径：{self.url}  请求方式：{self.method}  响应code值：{self.response.status_code}")
        # logger.info(f"请求头：{self.headers}")
        logger.info(f"响应内容：{self.response.json()}")

    # 封装输出请求信息和响应信息
    # def request_info(self):


# 感觉不用创建类 创建函数就可以了
# 接口请求封装函数
def r_requests(method, url, **kwargs):
    headers = None
    params = None
    json = None
    try:
        if method == 'get':
            response = requests.get(url, **kwargs)

        elif method == 'post':
            response = requests.post(url, **kwargs)

        elif method == 'put':
            response = requests.put(url, **kwargs)

        elif method == 'delete':
            response = requests.delete(url, **kwargs)

        else:
            logger.error(f"请求方式{method}错误，请检查！")
            # print(f"请求方式{method}错误，请检查！")

        if 'headers' in kwargs:
            headers = kwargs['headers']
        if 'params' in kwargs:
            params = kwargs['params']
        if 'json' in kwargs:
            json = kwargs['json']

        logger.info(f"请求路径：{url}  请求方式：{method}  请求头：{headers}  请求参数params：{params}  请求参数json：{json}")
        logger.info(f"响应code值：{response.status_code}  响应内容：{response.json()}")

        return response
    except Exception as e:
        logger.error(f"请求异常！异常信息为：{e}")


# 提取接口响应结果中，data的变量
def data_extract_value(response, extract_value_name):       # 如果请求成功 就提取data的变量
    if response.status_code == 200:     # 接口响应成功才能提取变量
        if 'data' in response.json() and extract_value_name in response.json()['data']:   # 判断提取的变量是否存在
            value = response.json()['data'][extract_value_name]
            logger.debug(f"接口[{extract_value_name}]变量提取成功! 变量值为：[{value}]")
            return value

        else:       # 提取的变量不存在
            logger.error(f"变量提取失败！响应结果-data中，没有[{extract_value_name}]的字段")

    else:
        logger.error(f"接口请求失败！响应内容：{response.json()}")

if __name__ == '__main__':
    json_data = {
        "mobile": "15900000038",
        "verifyCode": "111",
        "thirdType": 1,
        "type": "login",
        "cellphoneModel": "iPhone",
        "registerId": "714f53c52e894c1af69b5c60da21d2",
        "sign_params": "APP_ID=1577498216199&TIMESTAMP=20240820155247&SIGN_TYPE=SHA256&NONCE=113xoe7k8cn&SIGN=4707159681FE2E9EDBF000ED35D1FCF319678C3E93C27B71E2E6A617DC656F7F"
    }
    url = "https://day.ddm.qxdaojia.com/api/malluser/user/verify/validateCode"
    headers = {
        'content-type': 'application/json'
    }
    # req = Request('ddd_user')
    # rep = req.request('post', url, json=json_data)
    rp = r_requests('post', url, json=json_data, headers=headers)
    token = data_extract_value(rp, 'access_token')
    mm = data_extract_value(rp, 'mm')
    # print(token)









